import React, { useState, useRef } from 'react';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { ModalForm, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import type { ProFormInstance } from '@ant-design/pro-form';
import { Button, Tree } from 'antd';
import { Role } from '@/services/ant-design-pro/api';
import { DownOutlined } from '@ant-design/icons';

const treeDataList = [
  {
    id: '1',
    path: '/system',
    name: '系统管理',
    icon: 'crown',
    routes: [
      { id: '1-1', path: 'menu', name: '菜单管理', icon: 'smile', component: './system/menu' },
      { id: '1-2', path: 'role', name: '角色管理', icon: 'smile', component: './system/role' },
      { id: '1-3', path: 'user', name: '用户管理', icon: 'smile', component: './system/user' },
    ],
  },
];

// 树形数据-获取所有的Keys
function allKeysTreeData(data: any, allKeys: any) {
  data.forEach((v: any) => {
    const tmp = { ...v };
    allKeys.push(tmp.id);
    if (tmp.routes) {
      allKeysTreeData(tmp.routes, allKeys);
    }
  });
  return allKeys;
}
const treeDataKeys = allKeysTreeData(treeDataList, []);

// 处理树形数据
function filterAsyncTreeData(data: any) {
  const res: any = [];
  data.forEach((v: any) => {
    const tmp = { ...v };
    if (tmp.routes) {
      tmp.children = filterAsyncTreeData(tmp.routes);
    }
    res.push({
      key: tmp.id,
      title: tmp.name,
      expand: true,
      children: tmp.children,
    });
  });
  return res;
}
const treeData = filterAsyncTreeData(treeDataList);

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [RoleType, setRoleTypeChange] = useState('add');
  const [RoleVisible, setRoleVisible] = useState(false);
  const roleRestFormRef = useRef<ProFormInstance>();

  const [RoleMenuTitle, setRoleMenuTitle] = useState<string | undefined>('');
  const [RoleMenuVisible, setRoleMenuVisible] = useState(false);
  const RoleMenuFormRef = useRef<ProFormInstance>();
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>();

  const [AllCheckedVisible, setAllCheckedVisible] = useState(false);

  const [ExpandAllVisible, setExpandAllVisible] = useState(false);
  const [expandedKeys, setExpandedKeys] = useState([]);

  const formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 17 },
  };

  // 菜单权限
  const onSelect = (selectedKeys: React.Key[], info: any) => {
    console.log('selected', selectedKeys, info);
  };
  const onCheck = (checkedKeys: any, info: any) => {
    console.log('onCheck', checkedKeys, info.checkedNodes);

    setCheckedKeys(checkedKeys);
  };

  const columns: ProColumns<API.RoleListItem>[] = [
    {
      dataIndex: 'role_id',
      title: '角色ID',
    },
    {
      dataIndex: 'role_name',
      title: '角色名称',
    },
    {
      dataIndex: 'desc',
      title: '角色介绍',
      hideInSearch: true,
    },
    {
      dataIndex: 'option',
      valueType: 'option',
      title: '操作',
      render: (_, row) => [
        <a
          key="config"
          onClick={() => {
            setRoleTypeChange('edit');
            roleRestFormRef.current?.resetFields();
            setRoleVisible(true);

            roleRestFormRef?.current?.setFieldsValue({
              role_id: row.role_id,
              role_name: row.role_name,
              desc: row.desc,
            });
          }}
        >
          编辑
        </a>,
        <a
          key="config"
          onClick={() => {
            // setRoleTypeChange('edit')
            // roleRestFormRef.current?.resetFields();
            // setRoleVisible(true)

            // roleRestFormRef?.current?.setFieldsValue({
            //   role_id: row.role_id,
            //   role_name: row.role_name,
            //   desc: row.desc,
            // })

            setCheckedKeys([]);
            setExpandedKeys(treeDataKeys); // 默认展开所有
            setRoleMenuTitle(row.role_name);
            setRoleMenuVisible(true);
          }}
        >
          菜单权限
        </a>,
      ],
    },
  ];

  return (
    <PageContainer title="角色管理">
      {/* Table列表 */}
      <ProTable<API.RoleListItem, API.PageParams>
        headerTitle="角色管理列表"
        rowKey="key"
        actionRef={actionRef}
        options={{ fullScreen: true, reload: true, setting: true }}
        search={{ labelWidth: 120 }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setRoleTypeChange('add');
              roleRestFormRef.current?.resetFields();
              setRoleVisible(true);
            }}
          >
            新建
          </Button>,
        ]}
        request={Role}
        columns={columns}
      />

      {/* 新增编辑弹窗 */}
      <ModalForm
        formRef={roleRestFormRef}
        title={RoleType == 'add' ? '新增角色' : '编辑角色'}
        width="450px"
        visible={RoleVisible}
        onVisibleChange={setRoleVisible}
        {...formItemLayout}
        layout="horizontal"
        onFinish={async (values) => {
          console.log(values);
          setRoleVisible(true);
          return true;
        }}
      >
        {/* Form 表单 */}
        <ProFormText
          label="角色ID"
          rules={[
            {
              required: true,
              message: '角色ID为必填项',
            },
          ]}
          width="md"
          name="role_id"
        />
        <ProFormText
          label="角色名称"
          rules={[
            {
              required: true,
              message: '角色名称为必填项',
            },
          ]}
          width="md"
          name="role_name"
        />
        <ProFormTextArea label="角色介绍" width="md" name="desc" />
      </ModalForm>

      {/* 菜单权限-弹窗 */}
      <ModalForm
        formRef={RoleMenuFormRef}
        title={`分配 ${RoleMenuTitle} 的菜单权限`}
        width="450px"
        visible={RoleMenuVisible}
        onVisibleChange={setRoleMenuVisible}
        submitter={{
          render: (props, defaultDoms) => {
            return [
              // ...defaultDoms,
              <Button
                key="all"
                type="primary"
                ghost
                onClick={() => {
                  setExpandAllVisible(!ExpandAllVisible);
                  if (!ExpandAllVisible) {
                    setExpandedKeys(treeDataKeys);
                  } else {
                    setExpandedKeys([]);
                  }
                }}
              >
                全部收起
              </Button>,
              <Button
                key="all2"
                type="primary"
                ghost
                onClick={() => {
                  if (!AllCheckedVisible) {
                    setCheckedKeys(treeDataKeys);
                  } else {
                    setCheckedKeys([]);
                  }
                  setAllCheckedVisible(!AllCheckedVisible);
                }}
              >
                全部选择
              </Button>,
              defaultDoms[1],
            ];
          },
        }}
        onFinish={async (values) => {
          console.log(values);
          console.log(RoleMenuFormRef.current);
          return true;
        }}
      >
        <Tree
          switcherIcon={<DownOutlined />}
          expandedKeys={expandedKeys}
          checkStrictly={true}
          checkable
          checkedKeys={checkedKeys}
          onSelect={onSelect}
          onCheck={onCheck}
          treeData={treeData}
          onExpand={(Keys: any, { expanded }) => {
            setExpandAllVisible(expanded);
            setExpandedKeys(Keys);
          }}
        />
      </ModalForm>
    </PageContainer>
  );
};

export default TableList;
